package com.winning.bdu.core.utils;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;

/**
 * Author: yanxf@winning.com.cn
 * Description: http请求工具类
 * Date 2019/05/25 10:13
 */
public class HttpClientUtil {

    private static final int ConTimeOut = 30000;

    private static final int SoTimeOut = 120000;

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * httpPost: httpclient post方法 . <br/>
     * 支持重定向，支持请求转发
     *
     * @param url 请求地址
     * @param paramMap 请求参数
     * @param code 字符编码
     *
     * @return String
     *
     */
    public static String httpPost(String url, Map<String, String> paramMap, String code) {

        logger.info("GetPage:" + url);
        String content = null;
        if (url == null || url.trim().length() == 0 || paramMap == null || paramMap.isEmpty()) {
            return null;
        }
        HttpClient httpClient = new HttpClient();
        // 设置header
        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");//

        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, code);

        HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(ConTimeOut);
        managerParams.setSoTimeout(SoTimeOut);

        if (url.contains("https")) {
            Protocol myhttps = new Protocol("https", new MyProtocolSocketFactory(), 443);
            Protocol.registerProtocol("https", myhttps);
        }
        PostMethod method = new PostMethod(url);

        AppendPostParam(method, paramMap);//设置post方法参数
        try {
            int statusCode = httpClient.executeMethod(method);

            // 检查是否重定向
            if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                // 读取新的 URL 地址
                Header header = method.getResponseHeader("location");
                if (header != null) {
                    String newuri = header.getValue();
                    if ((newuri == null) || ("".equals(newuri))) {
                        newuri = "/";
                    }
                    method = new PostMethod(newuri);
                    AppendPostParam(method, paramMap);
                    statusCode = httpClient.executeMethod(method);
                }
            }
            logger.info("httpClientUtils::statusCode=" + statusCode);
            logger.info(method.getStatusLine().toString());
            content = new String(method.getResponseBody(), code);
            logger.info("response content:" + content);
        } catch (Exception e) {
            logger.info("time out");
        } finally {
            method.releaseConnection();
        }
        return content;
    }


    /**
     * AppendPostParam: 设置post方法发送参数 . <br/>
     *
     * @author tolly
     * @since JDK 1.8
     */
    private static void AppendPostParam(PostMethod method, Map<String, String> paramMap) {

        Iterator<?> it = paramMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next() + "";
            Object o = paramMap.get(key);
            if (o != null && o instanceof String) {
                method.addParameter(new NameValuePair(key, o.toString()));
            }
            if (o != null && o instanceof String[]) {
                String[] s = (String[]) o;
                if (s != null) {
                    for (int i = 0; i < s.length; i++) {
                        method.addParameter(new NameValuePair(key, s[i]));
                    }
                }
            }
        }
    }



}

